<template>
  <div class="page-main">
    <div class="cn-title">注册vip</div>
    <div class="cn-cont">
      <div class="form-wrap">
        <el-form
          :model="loginForm"
          label-width="80px"
          label-position="top"
          :rules="formRules"
          ref="loginFormRef"
        >
          <el-form-item label="手机号：" prop="phone">
            <el-input
              v-model.trim="loginForm.phone"
              placeholder="请输入手机号"
              size="large"
            />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input
              v-model.trim="loginForm.password"
              placeholder="请输入密码"
              size="large"
              type="password"
            />
          </el-form-item>
          <el-form-item label="确认密码:" prop="rePassword">
            <el-input
              v-model.trim="loginForm.rePassword"
              placeholder="请再次输入手机号"
              size="large"
              type="password"
            />
          </el-form-item>
          <el-form-item label="角色:" prop="role">
            <el-radio-group v-model="loginForm.role">
              <el-radio label="admin">管理员</el-radio>
              <el-radio label="vip">vip用户</el-radio>
              <el-radio label="visitor">游客</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="vip年限:" prop="expire" v-if="loginForm.role ==='vip'" :rules="[
            {
              required: true,
              message: 'vip年限不能为空',
              trigger: 'blur',
            },
          ]">
            <el-radio-group v-model="loginForm.expire">
              <el-radio :label="0.5">半年</el-radio>
              <el-radio :label="1">1年</el-radio>
              <el-radio :label="2">2年</el-radio>
              <el-radio :label="3">3年</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="验证码:" prop="inputVcode">
            <div class="guiCode-wrap">
              <el-input
                v-model.trim="loginForm.inputVcode"
                placeholder="请输入验证码"
                size="large"
              />
              <identifyCodeCom
                :identifyCode="identifyCode"
                @click="refreshIdentifyCode"
              ></identifyCodeCom>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              class="submit-btn"
              type="primary"
              @click="submitForm(loginFormRef)"
              size="large"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
// 登录弹窗
import identifyCodeCom from '@/components/identifyCode'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/api/fetch'
import { loadStore } from '@/store'
import { useRouter, useRoute } from 'vue-router'
const userStore = loadStore()
const router = useRouter()
const loginFormRef = ref(null)
// 操作分为登录login，register,update更改密码
const actionType = ref('login')
const loginForm = reactive({
  phone: '',
  code: '',
  oldPassword: '',
  password: '',
  rePassword: '',
  inputVcode: '',
  role: 'vip',
  expire:0.5
})
// 验证码
const identifyCode = ref('')
const reqLoading = ref(false)
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (loginForm.rePassword !== '') {
      if (!loginFormRef.value) return
      loginFormRef.value.validateField('rePassword', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== loginForm.password) {
    callback(new Error('两次密码必须相同'))
  } else {
    callback()
  }
}

const validateVcode = (rule, value, callback) => {
  if (identifyCode.value.toLowerCase() !== value.toLowerCase()) {
    callback(new Error('验证码错误'))
  } else {
    callback()
  }
}

let formRules = ref({
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      pattern:
      /^(0|86|17951)?(13[0-9]|15[012356789]|16[0-9]|17[0-9]|18[0-9]|19[0-9]|14[57])[0-9]{8}$/,
      message: '手机号格式错误',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  inputVcode: [
    { required: true, message: '验证码不能为空', trigger: 'change' },
    { validator: validateVcode, trigger: 'change' }
  ],
  rePassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  role: [{ required: true, message: '角色不能为空', trigger: 'blur' }]
})

function loginRegisterSuccess(res) {
  if (res) {
    userStore.setToken(res.token)
    userStore.setUserInfo(res.user)

    ElMessage({
      type: 'success',
      message: '注册成功'
    })
    setTimeout(() => {
      router.push({ path: '/address' })
    }, 0)
  }
  reqLoading.value = false
}
async function registerFn(queryObj) {
  reqLoading.value = true
  try {
    await request('/register', {
      method: 'POST',
      body: queryObj
    })
    router.push({path:'/login'})
    ElMessage({
      type:'success',
      message:'注册成功，请重新登录',
      duration:5000
    })
  } catch (error) {
    ElMessage({
      type:'error',
      message:'注册失败，请稍后重试',
      duration:5000
    })
  }
  

  // loginRegisterSuccess(res)
}

function submitForm(formEl) {
  // 提交表单
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      let queryObj = {
        phone: loginForm.phone,
        password: loginForm.password,
        role: loginForm.role,
      }
      if(loginForm.role==='vip'){
        queryObj.expire = loginForm.expire
      }
      registerFn(queryObj)
    } else {
      console.log('error submit!')
      return false
    }
  })
}

function makeIdentifyCode(l) {
  let identifyKey =
    '234567890abcdefghzklmnopqrstuvwxyzABCDEFGHZKLMNOPQRSTUVWXYZ'
  for (let i = 0; i < l; i++) {
    identifyCode.value += identifyKey[randomNum(0, identifyKey.length)]
  }
}
// 生成单个验证码
function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min)
}

function refreshIdentifyCode() {
  identifyCode.value = ''
  makeIdentifyCode(4)
}

onMounted(() => {
  makeIdentifyCode(4)
})
</script>
<style scoped lang="scss">
.page-main {
  min-height: calc(100vh - 120px);
  .cn-title {
    text-align: center;
    padding: 20px;
    box-sizing: border-box;
    font-size: 24px;
    font-weight: bold;
    height: 60px;
  }
  .cn-cont {
    margin: 0 auto;
    box-sizing: border-box;
    max-width: 1200px;
    margin: auto;
    padding: 20px 20px;
    background: white;
    min-height: calc(100vh - 120px);
    padding-bottom: 20px;
    .form-wrap {
      margin: auto;
      max-width: 320px;
      .el-form-item {
        margin-bottom: 18px;
      }
    }
  }
  .guiCode-wrap {
    display: flex;
    align-items: center;
    .guiCode {
      width: 64px;
      height: 64px;
    }
  }
  .submit-btn {
    width: 100%;
  }
  .link-btn {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    .el-button {
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
</style>
